﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SSHTunnel
{
    public partial class Form1 : Form
    {
        private static BlueSSH _blueSSH = new BlueSSH();
        private static AccountInfo _accountInfo = BlueSSH.Account;
        private static Process _process;
        private static int _porcessID = -1000;
        private static Timer _timer;
        private static Timer _countTimer;
        private static TimeSpan _timeSpan;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("输入图片中的字符");
            }
            else
            {
                SwapFunc();
            }
        }

        private void SwapFunc()
        {
            if (button1.Text.Equals("断开"))
            {
                button1.Text = "连接";
                if (_porcessID > 0)
                {
                    Process process = Process.GetProcessById(_porcessID);
                    if (process != null)
                    {
                        process.Kill();
                    }
                }
            }
            else if (button1.Text.Equals("连接"))
            {
                button1.Text = "断开";
                Connect();
            }
        }

        private void Connect()
        {
            _process = new Process();
            ProcessStartInfo info = new ProcessStartInfo();
            string arguments = "-N " + _accountInfo.UserName + "@" + _accountInfo.Host + " -P 80 -D 127.0.0.1:7070 -pw " + textBox1.Text + " -v";
            info.FileName = AppDomain.CurrentDomain.BaseDirectory + "/plink.exe";
            info.Arguments = arguments;
            info.CreateNoWindow = true;
            info.UseShellExecute = false;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError = true;

            _process.StartInfo = info;
            _process.OutputDataReceived += new DataReceivedEventHandler(PrintMessage);
            _process.ErrorDataReceived += new DataReceivedEventHandler(PrintMessage);
            _process.Start();
            _porcessID = _process.Id;
            _process.BeginOutputReadLine();
            _process.BeginErrorReadLine();
        }

        private void PrintMessage(object sender, DataReceivedEventArgs e)
        {
            this.textBox2.Invoke(new MethodInvoker(() =>
            {
                textBox2.ScrollToCaret();
                textBox2.AppendText("[" + DateTime.Now.ToString("HH:mm.ss") + "]" + e.Data + "\r\n");
            }));
        }

        private void RefreshAccount(object sender, EventArgs e)
        {
            _timer.Stop();
            _countTimer.Stop();
            button1.Text = "连接";

            if (_porcessID > 0)
            {
                Process process = Process.GetProcessById(_porcessID);
                if (process != null)
                {
                    process.Kill();
                }
            }

            do
            {
                _blueSSH.Refresh();
            } while (_accountInfo.Time.Subtract(DateTime.Now).TotalMinutes < 5);

            _timeSpan = _accountInfo.Time.Subtract(DateTime.Now);
            _timer.Interval = (int)_timeSpan.TotalMilliseconds;
            _timer.Start();
            _countTimer.Start();
            this.Invoke(new MethodInvoker(() =>
            {
                pictureBox1.Image = _accountInfo.Img;
                textBox3.Text = _timeSpan.Minutes.ToString();
                textBox4.Text = _timeSpan.Seconds.ToString();
            }));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_porcessID > 0)
            {
                Process process = Process.GetProcessById(_porcessID);
                if (process != null)
                {
                    process.Kill();
                }
            }
            this.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Invoke(new MethodInvoker(() =>
            {
                tabControl1.SelectedIndex = 1;
                _blueSSH.Refresh();

                _countTimer = new Timer();
                _countTimer.Interval = 1000;
                _countTimer.Tick += new EventHandler(RefreshTime);
                _countTimer.Start();

                _timeSpan = _accountInfo.Time.Subtract(DateTime.Now);
                _timer = new Timer();
                _timer.Interval = (int)_timeSpan.TotalMilliseconds;
                _timer.Tick += new EventHandler(RefreshAccount);
                _timer.Start();

                pictureBox1.Image = _accountInfo.Img;
                int minutes = _timeSpan.Minutes;
                int seconds = _timeSpan.Seconds;
                textBox3.Text = minutes >= 10 ? minutes.ToString() : "0" + minutes;
                textBox4.Text = seconds >= 10 ? seconds.ToString() : "0" + seconds;
            }));
        }

        private void RefreshTime(object sender, EventArgs e)
        {
            _timeSpan = _timeSpan.Add(-(new TimeSpan(0, 0, 1)));
            this.Invoke(new MethodInvoker(() =>
            {
                int minutes = _timeSpan.Minutes;
                int seconds = _timeSpan.Seconds;
                textBox3.Text = minutes >= 10 ? minutes.ToString() : "0" + minutes;
                textBox4.Text = seconds >= 10 ? seconds.ToString() : "0" + seconds;
            }));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Hide();

        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            notifyIcon1.ContextMenuStrip = contextMenuStrip1;
            contextMenuStrip1.Show(Cursor.Position.X + 10, Cursor.Position.Y - 10);

        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_porcessID > 0)
            {
                Process process = Process.GetProcessById(_porcessID);
                if (process != null)
                {
                    process.Kill();
                }
            }
            this.Dispose();
        }
    }
}
